<?php
namespace mylib;

class GetImageByurl
{
    /**
     * 获取远程图片并重命名
     * @return string $filename 返回新图片名
     * @param string $url 图片地址
     * @param string $filename 图片名, 空则自动生成新图片名
     * @param string $dir 图片存放目录, 空则本地生成目录
     * @param string $sign 新文件名标志(如_thumb, .lt, _middle等), 空则不加
     */
    public static function getImageByurl($url, $filename = "", $dir = "", $sign = '')
    {
        if ($url == "") {
            return false;
        }
        
        $file = self::downloadImg($url);
        
        if (!$file || !self::isImg($url)) {
            return false;
        }

        // 存临时文件tmp
        // $tmpname = $_SERVER['TEMP'] . '/tmp'.time(); //非 cli 命令行下 $_SERVER['TEMP']
        // $tmpname = 'tmp'.time();
        $tmpname = TEMP_PATH . 'tmp'.time(); // Tp 框架下缓存目录
        //以流的形式保存图片
        $write_fd = @fopen($tmpname, "a");
        @fwrite($write_fd, $file);  //将采集来的远程数据写入本地文件
        @fclose($write_fd);

        $ext = self::getEXTENSION($tmpname);

        if ($filename == "") {
            $filename = md5(time() . mt_rand(1, 9)) . $sign . '.' . $ext; //以时间另起名，在此可指定相对目录 ，未指定则表示同php脚本执行的当前目录
        }

        $date = date('Ymd', time());

        if (!$dir && !is_dir($date)) {
            mkdir($date);
            $dir = $date;
        }

        rename($tmpname, $dir . '/' . $filename);
        return $filename;  //返回文件名
    }

    //远程获取
    public static function downloadImg($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        //curl_setopt($curl, CURLOPT_REFERER,$url);
        // curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36");  //模拟浏览器访问
        curl_setopt($curl, CURLOPT_COOKIEJAR, 'cookie.txt');
        curl_setopt($curl, CURLOPT_COOKIEFILE, 'cookie.txt');
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 0);
        $values = curl_exec($curl);
        $info = curl_getinfo($curl);
        curl_close($curl);
        if ($info['http_code'] == 200) {
            return($values);
        } else {
            return false;
        }
    }

    public static function isImg($filename)
    {
        $file = fopen($filename, "rb");
        $bin = fread($file, 2);  // 只读2字节

        fclose($file);
        $strInfo = @unpack("C2chars", $bin);
        $typeCode = intval($strInfo['chars1'].$strInfo['chars2']);
        $fileType = '';

        if ($typeCode == 255216 /*jpg*/ || $typeCode == 7173 /*gif*/ || $typeCode == 13780 /*png*/) {
            return $typeCode;
        } else {
            // echo '仅允许上传jpg/jpeg/gif/png格式的图片！';
            return false;
        }
    }

    /**
     * 获取图片后缀名
     */
    public static function getEXTENSION($filename)
    {
        $mimetype = exif_imagetype($filename);
    
        switch ($mimetype) {
            case IMAGETYPE_GIF:
                return 'gif';
                break;
            case IMAGETYPE_JPEG:
                return 'jpg';
                break;
            case IMAGETYPE_PNG:
                return 'png';
                break;
            default:
                return 'jpg';
                break;
        }
    }
}
